<script setup>
import { ref, onMounted, reactive } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Search,
  RefreshRight
} from '@element-plus/icons-vue'
import { pageQuery, addDish, alterDish, deleteDish } from '@/api/dish'
import { getCatagoriesList } from '@/api/catagory'
import { filemanage } from '@/api/filemanage' // 导入封装的上传函数
// 状态数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const imageUrl = ref('')
// 搜索和分页参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  categoryId: null,
  status: null
})

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  categoryId: '',
  price: '',
  image: '',
  description: '',
  status: 1,
  springCost: '', // 改为驼峰
  summerCost: '', // 改为驼峰
  autumnCost: '', // 改为驼峰
  winterCost: '' // 改为驼峰
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择菜品分类', trigger: 'change' }
  ],
  price: [{ required: true, message: '请输入菜品价格', trigger: 'blur' }],
  springCost: [{ required: true, message: '请输入春季成本', trigger: 'blur' }],
  summerCost: [{ required: true, message: '请输入夏季成本', trigger: 'blur' }],
  autumnCost: [{ required: true, message: '请输入秋季成本', trigger: 'blur' }],
  winterCost: [{ required: true, message: '请输入冬季成本', trigger: 'blur' }]
}
// 分类选项
const categoryOptions = ref([])
// 状态选项
const statusOptions = [
  { value: 1, label: '起售' },
  { value: 2, label: '停售' }
]
// 获取分类列表
const getCategoryOptions = async () => {
  try {
    const res = await getCatagoriesList()
    if (res.code === 1) {
      categoryOptions.value = res.data.map((item) => ({
        id: item.id,
        name: item.name,
        type: item.type,
        sort: item.sort,
        status: item.status
      }))
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取菜品列表
const getDishList = async () => {
  loading.value = true
  try {
    const response = await pageQuery(queryParams)

    tableData.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    console.error('获取菜品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理图片上传前的验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    return false
  }
  if (!isLt2M) {
    return false
  }
  return true
}

// 修改后的上传处理函数
const handleUpload = async (options) => {
  try {
    const { file } = options
    const uploadFormData = new FormData()
    uploadFormData.append('file', file)

    const response = await filemanage(uploadFormData)

    // 假设成功响应的code为1
    formData.image = response.msg // 使用response.data而不是msg
    imageUrl.value = response.msg
    // 可以添加上传成功的提示
  } catch (error) {
    console.error('上传失败:', error)
  }
}
// 处理搜索
const handleSearch = () => {
  queryParams.page = 1
  getDishList()
}

// 处理重置
const handleReset = () => {
  Object.assign(queryParams, {
    name: '',
    categoryId: '',
    status: ''
  })
  handleSearch()
}

// 分页变化处理
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getDishList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getDishList()
}

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增菜品'
  // 重置表单数据
  Object.assign(formData, {
    id: '', // 新增时id置空
    name: '',
    categoryId: '',
    price: '',
    image: '',
    description: '',
    status: 1, // 默认起售
    springCost: '',
    summerCost: '',
    autumnCost: '',
    winterCost: ''
  })
  imageUrl.value = '' // 清空图片预览
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜品'
  // 填充表单数据
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    categoryId: row.categoryId,
    price: row.price,
    image: row.image,
    description: row.description,
    status: row.status,
    springCost: row.springCost,
    summerCost: row.summerCost,
    autumnCost: row.autumnCost,
    winterCost: row.winterCost
  })
  imageUrl.value = row.image // 显示当前图片
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await deleteDish(row.id)
    getDishList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}
// 表单提交
const formRef = ref(null)
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()

    // 构造提交的数据对象
    const submitData = {
      name: formData.name,
      categoryId: formData.categoryId,
      price: formData.price,
      image: formData.image,
      description: formData.description,
      status: formData.status,
      springCost: formData.springCost,
      summerCost: formData.summerCost,
      autumnCost: formData.autumnCost,
      winterCost: formData.winterCost
    }
    if (formData.id) {
      // 编辑模式
      submitData.id = formData.id
      await alterDish(submitData)
    } else {
      // 新增模式
      await addDish(submitData)
    }

    dialogVisible.value = false
    getDishList() // 刷新列表
  } catch (error) {
    console.error('提交失败:', error)
  }
}
// 生命周期钩子
onMounted(() => {
  getCategoryOptions()
  getDishList()
})
</script>

<template>
  <div class="dish-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="菜品名称">
          <div class="search-input-wrapper">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入菜品名称"
              clearable
              @keyup.enter="handleSearch"
              class="fixed-width-input"
            />
          </div>
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryId" class="custom-select">
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" class="custom-select">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="RefreshRight" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="handleAdd">
            新增菜品
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <!-- 表格列部分代码 -->
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="菜品名称" width="128" />
        <el-table-column label="菜品图片" width="140" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              fit="cover"
              class="dish-image"
            />
            <el-icon v-else><Picture /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="售价" width="120">
          <template #default="{ row }"> ¥{{ row.price }} </template>
        </el-table-column>
        <el-table-column label="春季成本" width="130">
          <template #default="{ row }"> ¥{{ row.springCost }} </template>
        </el-table-column>
        <el-table-column label="夏季成本" width="130">
          <template #default="{ row }"> ¥{{ row.summerCost }} </template>
        </el-table-column>
        <el-table-column label="秋季成本" width="130">
          <template #default="{ row }"> ¥{{ row.autumnCost }} </template>
        </el-table-column>
        <el-table-column label="冬季成本" width="130">
          <template #default="{ row }"> ¥{{ row.winterCost }} </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '起售' : '停售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品分类" prop="categoryId">
              <el-select v-model="formData.categoryId" placeholder="请选择分类">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品价格" prop="price">
              <el-input-number
                v-model="formData.price"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
                placeholder="请输入售价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品状态">
              <el-radio-group v-model="formData.status">
                <el-radio
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="春季成本" prop="springCcost">
              <el-input-number
                v-model="formData.springCost"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
                placeholder="请输入春季成本"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夏季成本" prop="summerCost">
              <el-input-number
                v-model="formData.summerCost"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
                placeholder="请输入夏季成本"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="秋季成本" prop="autumnCost">
              <el-input-number
                v-model="formData.autumnCost"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
                placeholder="请输入秋季成本"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="冬季成本" prop="winterCost">
              <el-input-number
                v-model="formData.winterCost"
                :precision="2"
                :step="0.1"
                :min="0"
                style="width: 100%"
                placeholder="请输入冬季成本"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="菜品图片">
          <el-upload
            class="avatar-uploader"
            :auto-upload="true"
            :show-file-list="false"
            :http-request="handleUpload"
            :before-upload="beforeImageUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dish-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-input-wrapper {
  position: relative;
  width: 200px; /* 设置固定宽度 */
}

.fixed-width-input {
  width: 100%;
}

/* 确保清除按钮位置正确 */
.fixed-width-input :deep(.el-input__clear) {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dish-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: contain;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

/* Form Styles */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-radio-group) {
  width: 100%;
  display: flex;
  gap: 20px;
}

/* Table Styles */
:deep(.el-table th) {
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-regular);
  font-weight: 500;
}

:deep(.el-table td) {
  padding: 8px 0;
}

/* Card Styles */
:deep(.el-card) {
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

/* Responsive Styles */
@media (max-width: 768px) {
  .el-form--inline .el-form-item {
    display: block;
    margin-right: 0;
    width: 100%;
  }

  .dish-management {
    padding: 12px;
  }

  .el-dialog {
    width: 90% !important;
    margin: 5vh auto !important;
  }

  .el-row {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }

  .el-col {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
}
</style>
